//
//  GMLoginViewController.m
//  GuardMan
//
//  Created by steven on 2016/12/15.
//  Copyright © 2016年 steven. All rights reserved.
//

#import "GMLoginViewController.h"
#import "GMForgetPasswordViewController.h"
#import "GMRegisterViewController.h"
#import "GMAuthTextField.h"
#import "GMLoginDataController.h"
#import "GMButton.h"
#import "GMDebtorListViewController.h"
#import "GMMenuViewController.h"
#import "GMNavigationController.h"
#import <MMDrawerController/MMDrawerController.h>

@interface GMLoginViewController ()

@property (nonatomic, strong)NSString *mobile;
@property (nonatomic, strong)NSString *password;

@property (nonatomic, strong)GMLoginDataController *loginDataController;

@end

@implementation GMLoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.loginDataController = [[GMLoginDataController alloc] init];
    // content view
    [self setupContentView];

}

#pragma mark - setupContentView
- (void)setupContentView {
    self.view.backgroundColor = [UIColor whiteColor];
    // logo view
    [self.view addSubview:self.logoImageView];
    [self.logoImageView autoPinEdgeToSuperviewEdge:ALEdgeTop withInset:56+64];
    [self.logoImageView autoAlignAxisToSuperviewAxis:ALAxisVertical];

    // password text field
    [self.view addSubview:self.passwordTextField];
    [self.passwordTextField autoAlignAxisToSuperviewAxis:ALAxisVertical];
    [self.passwordTextField autoAlignAxisToSuperviewAxis:ALAxisHorizontal];
    [self.passwordTextField autoSetDimensionsToSize:CGSizeMake(self.view.frame.size.width*0.8,AUTH_TEXT_FIELD_HEIGHT)];
    // phone text field
    [self.view addSubview:self.phoneTextField];
    [self.phoneTextField autoPinEdge:ALEdgeLeading toEdge:ALEdgeLeading ofView:self.passwordTextField];
    [self.phoneTextField autoPinEdge:ALEdgeBottom toEdge:ALEdgeTop ofView:self.passwordTextField withOffset:-14];
    [self.phoneTextField autoSetDimensionsToSize:CGSizeMake(self.view.frame.size.width*0.8, AUTH_TEXT_FIELD_HEIGHT)];

    // login button
    [self.view addSubview:self.loginButton];
    [self.loginButton autoAlignAxis:ALAxisVertical toSameAxisOfView:self.view];
    [self.loginButton autoPinEdge:ALEdgeTop toEdge:ALEdgeBottom ofView:self.passwordTextField withOffset:14];
    [self.loginButton autoSetDimensionsToSize:CGSizeMake(self.view.frame.size.width*0.8, AUTH_TEXT_FIELD_HEIGHT)];

    // register button
    [self.view addSubview:self.registerButton];
    [self.registerButton autoPinEdge:ALEdgeLeading toEdge:ALEdgeLeading ofView:self.loginButton withOffset:7];
    [self.registerButton autoPinEdge:ALEdgeTop toEdge:ALEdgeBottom ofView:self.loginButton withOffset:14];

    // forget password button
    [self.view addSubview:self.forgotPasswdButton];
    [self.forgotPasswdButton autoPinEdge:ALEdgeTrailing toEdge:ALEdgeTrailing ofView:self.loginButton withOffset:-7];
    [self.forgotPasswdButton autoPinEdge:ALEdgeTop toEdge:ALEdgeBottom ofView:self.loginButton withOffset:14];
}

#pragma mark - Forgot password button pressed
- (void)forgotPasswordButtonPressed {
    GMForgetPasswordViewController *forgotPasswordViewController = [[GMForgetPasswordViewController alloc] init];
    [self.navigationController pushViewController:forgotPasswordViewController animated:YES];
}

#pragma mark - Login button pressed
- (void)loginButtonPressed {
    if ([self checkInputValidation]) {
        // login now
        NSDictionary *params = @{@"phone_number":self.mobile,@"password":self.password};
        [self.loginDataController loginWithParams:params
                                         callback:^(NSString *error) {
                                             dispatch_async(dispatch_get_main_queue(), ^{
                                                 if (error == nil) {
                                                     // render success view
                                                     [self renderSuccessView];
                                                 } else {
                                                     [self showAlertMessage:error];
                                                 }
                                             });
                                             
                                         }];
    }
}

#pragma mark - Register button pressed
- (void)registerButtonPressed {
    GMRegisterViewController *registerViewController = [[GMRegisterViewController alloc] init];
    [self.navigationController pushViewController:registerViewController animated:YES];
}

#pragma mark - Check input validation
- (BOOL)checkInputValidation {
    [self.phoneTextField resignFirstResponder];
    [self.passwordTextField resignFirstResponder];
    
    self.mobile = self.phoneTextField.text;
    self.password = self.passwordTextField.text;
    if ((self.mobile.length == 11 || self.mobile.length == 14) && self.password.length > 0) {
        return YES;
    } else if (self.mobile.length == 0) {
        [self showAlertMessage:@"请输入手机号"];
    } else if(self.mobile.length != PHONE_LENGTH) {
        [self showAlertMessage:@"请输入正确的手机号"];
    } else if (self.password.length == 0) {
        // you can login now
        [self showAlertMessage:@"请输入密码"];
    }
    return NO;
}

#pragma mark - Render success view
- (void)renderSuccessView {
    NSDictionary *dict = self.loginDataController.response[@"data"];
    NSString *token = dict[@"token"];
    NSDictionary *userDict = dict[@"user"];
    NSString *userId = [userDict[@"id"] stringValue];
    NSString *name = userDict[@"name"];
    NSString *headImg = userDict[@"headImg"];
    NSString *type = userDict[@"type"];
    NSString *vip = [userDict[@"vip"] stringValue];
    NSString *mobile = userDict[@"account"];
    NSString *recommend = userDict[@"recommend"];
    
    NSLog(@"Login succeed\nid:%@\nname:%@\nToken:%@", userId, name, token);
    
    // store user info
    [[NSUserDefaults standardUserDefaults] setObject:userId forKey:@"userId"];
    [[NSUserDefaults standardUserDefaults] setObject:name forKey:@"name"];
    [[NSUserDefaults standardUserDefaults] setObject:headImg forKey:@"headImageUrl"];
    [[NSUserDefaults standardUserDefaults] setObject:token forKey:@"token"];
    [[NSUserDefaults standardUserDefaults] setObject:type forKey:@"type"];
    [[NSUserDefaults standardUserDefaults] setObject:vip forKey:@"vip"];
    [[NSUserDefaults standardUserDefaults] setObject:mobile forKey:@"mobile"];
    [[NSUserDefaults standardUserDefaults] setObject:recommend forKey:@"recommend"];
    [[NSUserDefaults standardUserDefaults] synchronize];

    [self setupMainViewController];
}

#pragma mark - set up main viewController
- (void)setupMainViewController {
    GMDebtorListViewController *clientViewController = [[GMDebtorListViewController alloc] init];
    GMMenuViewController *menuViewController = [[GMMenuViewController alloc] init];

    GMNavigationController *centerNavigationVC = [[GMNavigationController alloc] initWithRootViewController:clientViewController];
    GMNavigationController *leftNavigationVC = [[GMNavigationController alloc] initWithRootViewController:menuViewController];

    MMDrawerController *drawerController = [[MMDrawerController alloc] initWithCenterViewController:centerNavigationVC leftDrawerViewController:leftNavigationVC];
    drawerController.openDrawerGestureModeMask = MMOpenDrawerGestureModeAll;
    drawerController.closeDrawerGestureModeMask = MMCloseDrawerGestureModeAll;

    drawerController.maximumLeftDrawerWidth = 200.0;

    [[[UIApplication sharedApplication] delegate] window].rootViewController = drawerController;
}

#pragma mark - Getter for logoImageView
- (UIImageView *)logoImageView {
    if (!_logoImageView) {
        _logoImageView = [[UIImageView alloc] init];
        _logoImageView.image = [UIImage imageNamed:@"logo"];
    }
    
    return _logoImageView;
}

#pragma mark - Getter for phone text field
- (GMAuthTextField *)phoneTextField {
    if (!_phoneTextField) {
        _phoneTextField = [[GMAuthTextField alloc] init];
        _phoneTextField.placeholder = @"手机号";
        _phoneTextField.keyboardType = UIKeyboardTypeNumberPad;
    }
    
    return _phoneTextField;
}

#pragma mark - Getter for password text field
- (GMAuthTextField *)passwordTextField {
    if (!_passwordTextField) {
        _passwordTextField = [[GMAuthTextField alloc] init];
        _passwordTextField.secureTextEntry = YES;
        _passwordTextField.placeholder = @"密码";
    }
    
    return _passwordTextField;
}

#pragma mark - Getter for forget password
- (UIButton *)forgotPasswdButton {
    if (!_forgotPasswdButton) {
        _forgotPasswdButton = [[UIButton alloc] init];
        _forgotPasswdButton.titleLabel.font = [UIFont systemFontOfSize:AUTH_FONT_SIZE];
        [_forgotPasswdButton setTitleColor:BUTTON_ACTIVE_COLOR forState:UIControlStateNormal];
        [_forgotPasswdButton setTitle:@"忘记密码?" forState:UIControlStateNormal];
        [_forgotPasswdButton addTarget:self action:@selector(forgotPasswordButtonPressed) forControlEvents:UIControlEventTouchUpInside];
    }
    
    return _forgotPasswdButton;
}

#pragma mark - Getter for login button
- (GMButton *)loginButton {
    if (!_loginButton) {
        _loginButton = [[GMButton alloc] init];
        _loginButton.titleLabel.font = [UIFont systemFontOfSize:AUTH_FONT_SIZE];
        [_loginButton setTitle:@"登录" forState:UIControlStateNormal];
        [_loginButton addTarget:self action:@selector(loginButtonPressed) forControlEvents:UIControlEventTouchUpInside];
    }
    
    return _loginButton;
}

#pragma mark - Getter for register button
- (UIButton *)registerButton {
    if (!_registerButton) {
        _registerButton = [[UIButton alloc] init];
        [_registerButton setTitleColor:BUTTON_ACTIVE_COLOR forState:UIControlStateNormal];
        _registerButton.titleLabel.font = [UIFont systemFontOfSize:AUTH_FONT_SIZE];
        [_registerButton setTitle:@"注册新账号" forState:UIControlStateNormal];
        [_registerButton addTarget:self action:@selector(registerButtonPressed) forControlEvents:UIControlEventTouchUpInside];
    }
    
    return _registerButton;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    // Hide navigationbar
    [self.navigationController.navigationBar setHidden:YES];
    [self.navigationController.navigationBar setBarStyle:UIBarStyleDefault];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    // Hide navigationbar
    [self.navigationController.navigationBar setHidden:NO];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
